<template>
	<view class="chapterManagement">
		<left-right-contraction :leftWidth="220">
			<view slot="left">
				<view class="left-warp">
					<view class="l-w-top">
						<el-button type="text" icon="el-icon-back" :size="size" style="color: #888;" @click="goback">返回</el-button>
						<el-button type="text" icon="el-icon-circle-plus-outline" :size="size" @click="newlyBuild">新建</el-button>
						<el-button type="text" icon="el-icon-sort" :size="size" style="color: #888;" @click="sortFn">{{sort==true?'倒序':'正序'}}</el-button>
					</view>
					<view class="l-w-center">
						<view class="w-c-li" v-for="(item,index) in chapterList" :key="index" @click="clickChapter(item,index)">
							<view class="li-index">{{index+1}}</view>
							<view class="li-title lz-ellipsis-1">{{item.name}}</view>
						</view>
						<el-empty description="暂无数据" v-if="chapterList.length==0"></el-empty>
					</view>
				</view>
			</view>
			<view slot="right" style="height: 85%;">
				<view class="right-warp">
					<view class="r-w-top">
						<el-input class="r-w-top-title" v-model="form.title" placeholder="请输入章节标题" maxlength="30" show-word-limit></el-input>
					</view>
					<view class="r-w-center">
						<editor id="editor" class="ql-container" placeholder="章节内容字数在1000-50000字,超出请下章节上传" @input="changeEditor" @ready="readyEditor"></editor>
						<view class="ql-submit">
							<view class="mask">{{form.content.length>0?form.content.length-7:0}}/50000</view>
							<el-button type="success" icon="el-icon-circle-plus-outline" :size="size" @click="submit" plain>保存</el-button>
						</view>
					</view>
				</view>
			</view>
		</left-right-contraction>
	</view>
</template>

<script>
	let that
	import {
		mapState
	} from 'vuex'
	export default {
		components:{
		},
		computed: {
			...mapState('ui', ['size']),
			...mapState('user', ['userInfo'])
		},
		data() {
			return {
				params:{},
				sort:true,//倒序
				chapterList:[],//小说目录
				form:{
					type:'add',//添加还是编辑
					title:'',//章节标题
					content:'',//章节内容
					fileID:'',//如果是修改，修改的章节fileID
					index:0,//要修改的章节下标
				},
				editorCtx:null
			}
		},
		onLoad(option) {
			that = this
			that.params=JSON.parse(decodeURIComponent(option.data))
			//获取小说目录
			this.cacheGetStorage()
		},
		methods: {
			async clickChapter(item,num){
				let content = await that.requsetText(item.fileID)
				that.editorCtx.setContents({
					html:content,
				})
				that.form.type="edit"
				that.form.title=item.name
				that.form.content=content
				that.form.fileID=item.fileID
				that.form.index=num
			},
			readyEditor(){
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},
			changeEditor(e){
				try{
					this.form.content=e.detail.html.replace('<br>','')
				}catch(e){
					//TODO handle the exception
				}
			},
			//保存
			submit(){
				if(this.form.content.length<50000&&this.form.content.length>1000){
					if(this.form.title){
						if(that.form.type=="edit"){
							//编辑章节
							that.editBookChapter()
						}else{
							//添加章节
							that.addBookChapter()
						}
					}else{
						uni.showToast({
							title: '标题不能为空',
							icon:"none"
						});
					}
				}else{
					uni.showToast({
						title: '章节字数限制在【1000-50000】字',
						icon:"none"
					});
				}
			},
			//编辑章节
			editBookChapter(){
				//处理数据
				let content=this.processingData()
				let req={
					params:{
						bookId:that.params._id,//书的id
						title:that.form.title,//标题
						content:content,//内容
						fileID:that.form.fileID,//要修改的章节fileID
						urlname:that.params.bookAuthor+'/'+that.params.bookName+'/'+that.form.title,//云存储中的文件名
					},
					active:'editBookChapter',
					showLoad: true,
				}
				uni.$lizhao.doCloud('set-books-cloud',req).then(res=>{
					console.log(res);
					if(res.code==0&&res.data){
						that.$message.success('保存成功')
						//获取小说目录
						that.cacheGetStorage()
					}
				})
			},
			//处理数据
			processingData(){
				let reg1= new RegExp('<p>','g')
				let reg2= new RegExp('</p>','g')
				let reg3= new RegExp('\t','g')
				let reg4= new RegExp(' ','g')
				let content=this.form.content.replace(reg1,'&nbsp;&nbsp;&nbsp;&nbsp;').replace(reg2,'\n<br>\n<br>').replace(reg3,'').replace(reg4,'')
				return content
			},
			//添加章节
			addBookChapter(){
				//处理数据
				let content=this.processingData()
				let req={
					params:{
						bookId:that.params._id,//书的id
						title:that.form.title,//标题
						content:content,//内容
						urlname:that.params.bookAuthor+'/'+that.params.bookName+'/'+that.form.title,//云存储中的文件名
					},
					active:'addBookChapter',
					showLoad: true,
				}
				uni.$lizhao.doCloud('set-books-cloud',req).then(res=>{
					console.log(res);
					if(res.code==0&&res.data){
						that.$message.success('保存成功')
						that.form.type="edit"
						//获取小说目录
						that.cacheGetStorage()
					}
				})
			},
			//新建
			newlyBuild(){
				let num = this.chapterList.length + 1
				that.form.type="add"
				that.form.title=`第${num}章节`
				that.form.content=''
				that.form.fileID=''
				that.form.index=this.chapterList.length
				that.editorCtx.setContents({
					html:'',
				})
			},
			//获取目录
			cacheGetStorage(){
				let req={
					params:{
						bookId:that.params._id
					},
					active:'getBookMenu',
					showLoad: true,
				}
				uni.$lizhao.doCloud('get-books',req).then(async res=>{
					console.log(res);
					if(res.code==0&&res.data){
						that.chapterList=res.data[0].chapterList
						if(that.form.type=='edit'){
							that.form.fileID=that.chapterList[that.form.index].fileID
						}
					}
				})
			},
			//返回
			goback(){
				uni.navigateBack({
					delta: 1
				});
			},
			//排序
			sortFn(){
				this.sort=!this.sort
			},
			requsetText(url){
				return new Promise((resolve,reject)=>{
					uni.request({
						url,
						method: 'GET',
						data: {},
						success: res => {
							if(res.statusCode==200){
								let exp=new RegExp('&nbsp;&nbsp;&nbsp;&nbsp;','g')
								let exp2=new RegExp('\n<br>\n<br>','g')
								res.data=res.data.replace(exp,'<p>').replace(exp2,'</p>')
								resolve(res.data)
							}else{
								resolve('')
							}
						},
						fail: () => {},
						complete: () => {}
					});
				})
				
			},
		}
	}
</script>
<style lang="scss">
	page{width: 100%;height: 100%;}
	.chapterManagement {
		width: 100%;height: 100%;
		.left-warp{
			padding: 20rpx;box-sizing: border-box;
			.l-w-top{
				display: flex;justify-content: space-between;
			}
			.l-w-center{
				padding: 10px 0;box-sizing: border-box;
				.w-c-li{
					display: flex;justify-content: space-between;align-items: center;font-size: 14px;cursor: pointer;line-height: 24px;color: #6b6b6b;
					.li-index{
						color: #bababa;margin-right: 10rpx;font-size: 12px;
					}
					.li-title{flex: 1;}
				}
			}
		}
		.right-warp{
			padding: 30rpx 60rpx;box-sizing: border-box;height: 100%;
			.r-w-top{
				font-size: 30rpx;
			}
			.r-w-center{
				margin-top: 20rpx;height: 100%;
				.ql-container{
					height: 100%;line-height: 30px;color: #7d7d7d;
				}
				.ql-submit{
					float: right;color: #888;
					.mask{margin-bottom: 10px;font-size: 24rpx;}
				}
			}
		}
		
	}
</style>
